package com.castle.fortress.admin.contractType.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.castle.fortress.admin.core.constants.GlobalConstants;
import com.castle.fortress.admin.contractType.entity.ContractTypeEntity;
import com.castle.fortress.admin.contractType.dto.ContractTypeDto;
import com.castle.fortress.admin.contractType.dto.ContractTypeTreeDto;
import com.castle.fortress.admin.contractType.service.ContractTypeService;
import com.castle.fortress.common.utils.ConvertUtil;
import com.castle.fortress.common.entity.RespBody;
import com.castle.fortress.common.exception.BizException;
import com.castle.fortress.common.respcode.GlobalRespCode;
import com.castle.fortress.common.enums.OperationTypeEnum;
import com.castle.fortress.admin.core.annotation.CastleLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;
import org.apache.logging.log4j.util.Strings;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;
import com.castle.fortress.admin.utils.ExcelUtils;
import javax.servlet.http.HttpServletResponse;
import com.castle.fortress.common.entity.DynamicExcelEntity;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 合同类型表 控制器
 *
 * @author
 * @since 2025-04-22
 */
@Api(tags="合同类型表管理控制器")
@Controller
public class ContractTypeController {
    @Autowired
    private ContractTypeService contractTypeService;

    /**
     * 合同类型表的分页展示（树形结构）
     * @param contractTypeDto 合同类型表实体类
     * @param current 当前页
     * @param size  每页记录数
     * @return
     */
    @CastleLog(operLocation="合同类型表",operType = OperationTypeEnum.QUERY)
    @ApiOperation("合同类型表分页展示（树形结构）")
    @GetMapping("/contractType/contractType/page")
    @ResponseBody
    @RequiresPermissions("contractType:contractType:pageList")
    public RespBody<IPage<ContractTypeTreeDto>> pageContractType(ContractTypeDto contractTypeDto, @RequestParam(required = false) Integer current, @RequestParam(required = false)Integer size){
        Integer pageIndex= current==null? GlobalConstants.DEFAULT_PAGE_INDEX:current;
        Integer pageSize= size==null? GlobalConstants.DEFAULT_PAGE_SIZE:size;
        Page<ContractTypeTreeDto> page = new Page(pageIndex, pageSize);
        IPage<ContractTypeTreeDto> pages = contractTypeService.pageContractType(page, contractTypeDto);
        return RespBody.data(pages);
    }

    /**
     * 合同类型表的列表展示（树形结构）
     * @param contractTypeDto 合同类型表实体类
     * @return
     */
    @CastleLog(operLocation="合同类型表",operType = OperationTypeEnum.QUERY)
    @ApiOperation("合同类型表列表展示（树形结构）")
    @GetMapping("/contractType/contractType/list")
    @ResponseBody
    public RespBody<List<ContractTypeTreeDto>> listContractType(ContractTypeDto contractTypeDto){
        List<ContractTypeTreeDto> tree = contractTypeService.listContractType(contractTypeDto);
        return RespBody.data(tree);
    }

    /**
     * 合同类型表保存
     * @param contractTypeDto 合同类型表实体类
     * @return
     */
    @CastleLog(operLocation="合同类型表",operType = OperationTypeEnum.INSERT)
    @ApiOperation("合同类型表保存")
    @PostMapping("/contractType/contractType/save")
    @ResponseBody
    @RequiresPermissions("contractType:contractType:save")
    public RespBody<String> saveContractType(@RequestBody ContractTypeDto contractTypeDto){
        if(contractTypeDto == null ){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        ContractTypeEntity contractTypeEntity = ConvertUtil.transformObj(contractTypeDto,ContractTypeEntity.class);
        if(contractTypeService.save(contractTypeEntity)){
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 合同类型表编辑
     * @param contractTypeDto 合同类型表实体类
     * @return
     */
    @CastleLog(operLocation="合同类型表",operType = OperationTypeEnum.UPDATE)
    @ApiOperation("合同类型表编辑")
    @PostMapping("/contractType/contractType/edit")
    @ResponseBody
    @RequiresPermissions("contractType:contractType:edit")
    public RespBody<String> updateContractType(@RequestBody ContractTypeDto contractTypeDto){
        if(contractTypeDto == null || contractTypeDto.getId() == null || contractTypeDto.getId().equals(0L)){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        ContractTypeEntity contractTypeEntity = ConvertUtil.transformObj(contractTypeDto,ContractTypeEntity.class);
        if(contractTypeService.updateById(contractTypeEntity)){
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 合同类型表删除
     * @param id
     * @return
     */
    @CastleLog(operLocation="合同类型表",operType = OperationTypeEnum.DELETE)
    @ApiOperation("合同类型表删除")
    @PostMapping("/contractType/contractType/delete")
    @ResponseBody
    @RequiresPermissions("contractType:contractType:delete")
    public RespBody<String> deleteContractType(@RequestParam Long id){
        if(id == null ){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        if(contractTypeService.removeById(id)) {
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }


    /**
     * 合同类型表批量删除
     * @param ids
     * @return
     */
    @CastleLog(operLocation="合同类型表",operType = OperationTypeEnum.DELETE)
    @ApiOperation("合同类型表批量删除")
    @PostMapping("/contractType/contractType/deleteBatch")
    @ResponseBody
    @RequiresPermissions("contractType:contractType:deleteBatch")
    public RespBody<String> deleteContractTypeBatch(@RequestBody List<Long> ids){
        if(ids == null || ids.size()<1){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        if(contractTypeService.removeByIds(ids)) {
            return RespBody.data("保存成功");
        }else{
            return RespBody.fail(GlobalRespCode.OPERATE_ERROR);
        }
    }

    /**
     * 合同类型表详情
     * @param id 合同类型表id
     * @return
     */
    @CastleLog(operLocation="合同类型表",operType = OperationTypeEnum.QUERY)
    @ApiOperation("合同类型表详情")
    @GetMapping("/contractType/contractType/info")
    @ResponseBody
    @RequiresPermissions("contractType:contractType:info")
    public RespBody<ContractTypeDto> infoContractType(@RequestParam Long id){
        if(id == null){
            throw new BizException(GlobalRespCode.PARAM_MISSED);
        }
        ContractTypeEntity contractTypeEntity = contractTypeService.getById(id);
        ContractTypeDto contractTypeDto = ConvertUtil.transformObj(contractTypeEntity,ContractTypeDto.class);

        return RespBody.data(contractTypeDto);
    }

	/**
     * 动态表头导出 依据展示的字段导出对应报表
     * @param dynamicExcelEntity
     * @param response
     * @throws Exception
     */
    @CastleLog(operLocation="合同类型表",operType = OperationTypeEnum.EXPORT)
	@PostMapping("/contractType/contractType/exportDynamic")
	@ApiOperation("动态表头导出，依据展示的字段导出对应报表")
	public void exportDynamic(@RequestBody DynamicExcelEntity<ContractTypeDto> dynamicExcelEntity, HttpServletResponse response) throws Exception {
		List<ContractTypeTreeDto> treeList = contractTypeService.listContractType(dynamicExcelEntity.getDto());
		// 将树形结构转换为扁平列表
		List<ContractTypeDto> list = flattenTree(treeList);
		//字典、枚举、接口、json常量等转义后的列表数据 根据实际情况初始化该对象，null为list数据直接导出
		List<List<Object>> dataList = null;
		/**
        * 根据实际情况初始化dataList,可参照 com.castle.fortress.admin.system.controller.TmpDemoController类中方法：exportDynamic
        */
		ExcelUtils.exportDynamic(response,dynamicExcelEntity.getFileName()+".xlsx",null,list,dynamicExcelEntity.getHeaderList(),dataList);
	}

    /**
     * 将树形结构转换为扁平列表
     * @param treeList 树形结构列表
     * @return 扁平列表
     */
    private List<ContractTypeDto> flattenTree(List<ContractTypeTreeDto> treeList) {
        List<ContractTypeDto> result = new ArrayList<>();
        for (ContractTypeTreeDto node : treeList) {
            result.add(convertToDto(node));
            if (node.getChildren() != null && !node.getChildren().isEmpty()) {
                result.addAll(flattenTree(node.getChildren()));
            }
        }
        return result;
    }

    /**
     * 将树形节点转换为DTO
     * @param treeDto 树形节点
     * @return DTO对象
     */
    private ContractTypeDto convertToDto(ContractTypeTreeDto treeDto) {
        ContractTypeDto dto = new ContractTypeDto();
        dto.setId(treeDto.getId());
        dto.setTypeName(treeDto.getTypeName());
        dto.setTypeValue(treeDto.getTypeValue());
        dto.setLevel(treeDto.getLevel());
        dto.setParentId(treeDto.getParentId());
        dto.setSortOrder(treeDto.getSortOrder());
        return dto;
    }
}
